using System;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using ADODB;

namespace DWSchema
{
	/// <summary>
	/// Summary description for DWSchemaExplorer.
	/// </summary>
	public class DWSchemaExplorer : System.Windows.Forms.Form
	{
		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.TreeView treeView1;
		private System.Windows.Forms.ListView listView1;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem menuItem2;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.MenuItem menuItem4;
		private System.Windows.Forms.MenuItem menuItem10;
		private System.Windows.Forms.MenuItem menuItem11;
		private System.Windows.Forms.Splitter splitter1;
		private System.ComponentModel.IContainer components;
		private System.Windows.Forms.ColumnHeader columnHeader1;
		private System.Windows.Forms.ImageList imageList1;

		/// <summary>
		/// connection to the data warehouse
		/// </summary>
		private Connection con = new ConnectionClass();
		private System.Windows.Forms.ContextMenu contextMenu1;
		private System.Windows.Forms.MenuItem menuItem5;
		private System.Windows.Forms.MenuItem menuItem6;
		private HybridDictionary m_colRelations = new HybridDictionary();

		private string serverName = string.Empty;
		private string databaseName = string.Empty;
		private string userName = string.Empty;
		private string password = string.Empty;

		public DWSchemaExplorer()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(DWSchemaExplorer));
			this.mainMenu1 = new System.Windows.Forms.MainMenu();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.menuItem2 = new System.Windows.Forms.MenuItem();
			this.menuItem3 = new System.Windows.Forms.MenuItem();
			this.menuItem4 = new System.Windows.Forms.MenuItem();
			this.menuItem10 = new System.Windows.Forms.MenuItem();
			this.menuItem11 = new System.Windows.Forms.MenuItem();
			this.treeView1 = new System.Windows.Forms.TreeView();
			this.imageList1 = new System.Windows.Forms.ImageList(this.components);
			this.listView1 = new System.Windows.Forms.ListView();
			this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
			this.splitter1 = new System.Windows.Forms.Splitter();
			this.contextMenu1 = new System.Windows.Forms.ContextMenu();
			this.menuItem5 = new System.Windows.Forms.MenuItem();
			this.menuItem6 = new System.Windows.Forms.MenuItem();
			this.SuspendLayout();
			// 
			// mainMenu1
			// 
			this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.menuItem1,
																					  this.menuItem10});
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 0;
			this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.menuItem2,
																					  this.menuItem3,
																					  this.menuItem4});
			this.menuItem1.Text = "&File";
			// 
			// menuItem2
			// 
			this.menuItem2.Index = 0;
			this.menuItem2.Text = "&Connect";
			this.menuItem2.Click += new System.EventHandler(this.Connect);
			// 
			// menuItem3
			// 
			this.menuItem3.Index = 1;
			this.menuItem3.Text = "-";
			// 
			// menuItem4
			// 
			this.menuItem4.Index = 2;
			this.menuItem4.Text = "E&xit";
			// 
			// menuItem10
			// 
			this.menuItem10.Index = 1;
			this.menuItem10.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					   this.menuItem11});
			this.menuItem10.Text = "&Help";
			// 
			// menuItem11
			// 
			this.menuItem11.Index = 0;
			this.menuItem11.Text = "&About";
			this.menuItem11.Click += new System.EventHandler(this.menuItem11_Click);
			// 
			// treeView1
			// 
			this.treeView1.ContextMenu = this.contextMenu1;
			this.treeView1.Dock = System.Windows.Forms.DockStyle.Left;
			this.treeView1.ImageList = this.imageList1;
			this.treeView1.Location = new System.Drawing.Point(0, 0);
			this.treeView1.Name = "treeView1";
			this.treeView1.Size = new System.Drawing.Size(184, 265);
			this.treeView1.TabIndex = 0;
			this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown);
			this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
			// 
			// imageList1
			// 
			this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
			this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
			this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
			// 
			// listView1
			// 
			this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																						this.columnHeader1});
			this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
			this.listView1.Location = new System.Drawing.Point(184, 0);
			this.listView1.Name = "listView1";
			this.listView1.Size = new System.Drawing.Size(216, 265);
			this.listView1.TabIndex = 1;
			this.listView1.View = System.Windows.Forms.View.Details;
			// 
			// columnHeader1
			// 
			this.columnHeader1.Text = "Class Name";
			this.columnHeader1.Width = 211;
			// 
			// splitter1
			// 
			this.splitter1.Location = new System.Drawing.Point(184, 0);
			this.splitter1.Name = "splitter1";
			this.splitter1.Size = new System.Drawing.Size(3, 265);
			this.splitter1.TabIndex = 2;
			this.splitter1.TabStop = false;
			// 
			// contextMenu1
			// 
			this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						 this.menuItem5,
																						 this.menuItem6});
			// 
			// menuItem5
			// 
			this.menuItem5.Index = 0;
			this.menuItem5.Text = "Childern";
			this.menuItem5.Click += new System.EventHandler(this.menuItem5_Click);
			// 
			// menuItem6
			// 
			this.menuItem6.Index = 1;
			this.menuItem6.Text = "Properties...";
			this.menuItem6.Click += new System.EventHandler(this.menuItem6_Click);
			// 
			// DWSchemaExplorer
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(400, 265);
			this.Controls.Add(this.splitter1);
			this.Controls.Add(this.listView1);
			this.Controls.Add(this.treeView1);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Menu = this.mainMenu1;
			this.Name = "DWSchemaExplorer";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "DW Schema Explorer";
			this.Load += new System.EventHandler(this.DWSchemaExplorer_Load);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new DWSchemaExplorer());
		}

		private void DWSchemaExplorer_Load(object sender, System.EventArgs e)
		{
			Connect(this, e);
		}

		/// <summary>
		/// Connect the the DW database and get schema
		/// </summary>
		private void Connect(object sender, System.EventArgs e)
		{
			try
			{
				Connect frmCon = new Connect();
				if(DialogResult.OK == frmCon.ShowDialog(this))
				{
					serverName = frmCon.textBox1.Text;
					databaseName = frmCon.textBox2.Text;
					userName = frmCon.textBox3.Text;
					password = frmCon.textBox4.Text;

					GetCon(serverName, databaseName, userName, password);
					// now that we have connected get the schema
					LoadRoot();
				}
				else
				{
					Application.Exit();
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		/// <summary>
		/// Loads the class hierarchy in the root of the treeview.
		/// </summary>
		private void LoadRoot()
		{
			// clear the workspace
			m_colRelations.Clear();
			treeView1.Nodes.Clear();
			treeView1.Sorted = true;
    
			ADODB.Record oClasses = new RecordClass();
			oClasses.Open("ClassNames", con, ConnectModeEnum.adModeReadWrite, RecordCreateOptionsEnum.adCreateOverwrite, RecordOpenOptionsEnum.adOpenRecordUnspecified, string.Empty, string.Empty);

			LoadRelations();

			foreach(string name in (System.Array)oClasses.Fields["ClassNames"].Value)
			{
				TreeNode tn = treeView1.Nodes.Add(name);
				LoadChildren(name, name, tn);
			}
		}
		
		/// <summary>
		/// Loads the classes that are children of the specified class into the tree view.
		/// </summary>
		/// <param name="strClassName">The name of the class to load the children for.</param>
		/// <param name="strClassKey">The key in the treeview for the class we are loading children for.</param>
		private void LoadChildren(string strClassName, string strClassKey, TreeNode tn)
		{
			//System.Diagnostics.Debug.WriteLine(tn.Text);

			foreach(DictionaryEntry key in m_colRelations)
			{
				Record oRelation = (Record)key.Value;

				if(oRelation.Fields["ParentClassName"].Value.ToString() == strClassName)
				{
					string relationName = oRelation.Fields["ChildClassName"].Value.ToString();
					bool exists = false;
					// make sure that the node does not exist
					foreach(TreeNode loopnode in tn.Nodes)
					{
						if(loopnode.Text == relationName)
						{
							exists = true;
							break;
						}
					}
					
					if(!exists)
					{
						TreeNode tn2 = tn.Nodes.Add(relationName);
						LoadChildren(relationName, strClassKey+@"\"+relationName, tn2);
					}
				}																																																					 
			}
		}

		/// <summary>
		/// Loads the relation records from the data warehouse into a collection.
		/// </summary>
		private void LoadRelations()
		{
			Record oRelations = new RecordClass();
			
			oRelations.Open("RelationNames", con, ConnectModeEnum.adModeReadWrite, RecordCreateOptionsEnum.adCreateOverwrite, RecordOpenOptionsEnum.adOpenRecordUnspecified, string.Empty, string.Empty);

			foreach(string strRelation in (System.Array)oRelations.Fields["ClassNames"].Value)
			{
				Record oRelation = new RecordClass();
				oRelation.Open("relation/"+strRelation, con, ConnectModeEnum.adModeReadWrite, RecordCreateOptionsEnum.adCreateOverwrite, RecordOpenOptionsEnum.adOpenRecordUnspecified, string.Empty, string.Empty);
				m_colRelations.Add(strRelation, oRelation);
			}
		}
		
		/// <summary>
		/// Sets the version and app name captions
		/// </summary>
		/// <param name="server">The name of the data warehouse server.</param>
		/// <param name="database">The name of the data warehouse database.</param>
		/// <param name="user">The user name to connect to the database with.</param>
		/// <param name="password">The password for the database user.</param>
		private void GetCon(string server, string database,string user, string password)
		{
			con.Open("URL=mscop://InProcConnect/server="+server+":database="+database+":Catalog=DWSchema: user="+user+":password="+password+":FastLoad=True", string.Empty, string.Empty, 0);
		}

		private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
		{
			// if we have childern then show it in the list view
			
		}

		private void menuItem11_Click(object sender, System.EventArgs e)
		{
			About abt = new About();
			abt.ShowDialog(this);
		}

		private void menuItem5_Click(object sender, System.EventArgs e)
		{
			// clear the workspace
			listView1.Items.Clear();
			
			// get the current node
			foreach(TreeNode oNode in treeView1.SelectedNode.Nodes)
			{
				listView1.Items.Add(oNode.Text);
			}
		}

		private void menuItem6_Click(object sender, System.EventArgs e)
		{
			Class cls = new Class(serverName, databaseName, userName, password);
			cls.className = treeView1.SelectedNode.Text;
			cls.ShowDialog(this);
    	}

		private void treeView1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			// only work with the right button
			if(e.Button == MouseButtons.Right)
			{
				Point p = new Point(e.X, e.Y);
				TreeNode tnode = treeView1.GetNodeAt(p);
				treeView1.SelectedNode = tnode;
			}
		}
	}
}
